import sys
import os
import subprocess
from PySide6.QtWidgets import (
    QApplication, QWidget, QVBoxLayout, QGridLayout,
    QLabel, QLineEdit, QPushButton
)
from PySide6.QtGui import QIcon
from PySide6.QtWidgets import QHBoxLayout, QFileDialog  # 新增导入

class PhraseConfigWindow(QWidget):
    @staticmethod
    def resource_path(relative_path):
        """适配 PyInstaller 的资源路径处理"""
        try:
            # 打包后的资源路径（PyInstaller创建的临时文件夹）
            base_path = sys._MEIPASS
        except AttributeError:
            # 开发环境路径处理
            base_path = os.path.abspath(".")

        return os.path.join(base_path, relative_path)


    def __init__(self):
        super().__init__()
        self.setWindowTitle("小白输入法快捷短语配置面板")
        # 原代码修改
        self.setWindowIcon(QIcon(self.resource_path("ico/xiaobait9.ico")))

        self.resize(600, 400)

        # 创建主布局
        main_layout = QVBoxLayout()

        # 创建网格布局用于输入项
        grid_layout = QGridLayout()

        # 生成9个标签和输入框
        self.line_edits = []
        for i in range(9):
            # 创建标签
            label = QLabel(f"（{i + 1}）:")
            # 创建输入框
            line_edit = QLineEdit()
            self.line_edits.append(line_edit)

            # 添加到网格布局
            grid_layout.addWidget(label, i, 0)
            grid_layout.addWidget(line_edit, i, 1)

        # 创建路径选择组件（添加在保存按钮之前）
        path_layout = QHBoxLayout()
        self.path_edit = QLineEdit(r"请选择小白输入法的路径")
        path_btn = QPushButton("选择路径")
        path_btn.clicked.connect(self.select_target_path)

        path_layout.addWidget(QLabel("目标路径："))
        path_layout.addWidget(self.path_edit)
        path_layout.addWidget(path_btn)

        # 创建保存按钮
        save_btn = QPushButton("保存配置")
        save_btn.clicked.connect(self.save_config)

        # 组合布局
        main_layout.addLayout(grid_layout)
        main_layout.addLayout(path_layout)  # 新增路径布局
        main_layout.addWidget(save_btn)

        self.setLayout(main_layout)

    def select_target_path(self):
        """新增的路径选择方法"""
        directory = QFileDialog.getExistingDirectory(self, "选择保存目录", self.path_edit.text())
        if directory:
            self.path_edit.setText(directory)

    def save_config(self):
        target_path = self.path_edit.text().strip() + r"\data\dicts\xiaobai_quick_phrase.dict.yaml"

        try:
            # 读取文件内容
            with open(target_path, 'r', encoding='utf-8') as f:
                lines = f.readlines()

            # 查找标记行位置
            insert_index = -1
            for i, line in enumerate(lines):
                if "#quick phrase" in line:
                    insert_index = i
                    break

            if insert_index == -1:
                print("未找到#quick phrase标记")
                return

            # 保留到标记行（含），并处理换行符
            new_content = lines[:insert_index+1]

            # 确保标记行以换行符结尾
            if not new_content[-1].endswith('\n'):
                new_content[-1] += '\n'

            # 添加新的短语配置
            for idx, edit in enumerate(self.line_edits, 1):
                phrase = edit.text().strip()
                if phrase:
                    new_content.append(f"{phrase}\t766{idx}\n")

            # 写回文件
            with open(target_path, 'w', encoding='utf-8') as f:
                f.writelines(new_content)

            print("配置已成功保存到:", target_path)

            # 新增部署逻辑
            deployer_path = os.path.join(self.path_edit.text().strip(), "WeaselDeployer.exe")
            if os.path.exists(deployer_path):
                try:
                    subprocess.run(
                        [deployer_path, "/deploy"],
                        cwd=os.path.dirname(deployer_path),  # 设置工作目录
                        check=True
                    )
                    print("输入法部署成功")
                except subprocess.CalledProcessError as e:
                    print(f"部署失败，错误代码: {e.returncode}")
                except Exception as e:
                    print("部署异常:", str(e))
            else:
                print(f"部署工具不存在: {deployer_path}")

        except Exception as e:
            print("保存失败:", str(e))


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = PhraseConfigWindow()
    window.show()
    sys.exit(app.exec())
